<?php
/**
* @author		Arunoda Susiripala
* @package		jconnect
* @copyright	Arunoda Susiripala
* @license 		http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
*/

include('xmlrpc/xmlrpc.inc.php');
include('xmlrpc/xmlrpcs.inc.php');

class Joomla{
	public $appName;
	public $secretKey='99027k';
	public $host='localhost';
	public $path='/gsoc/JConnect/exApps/fake/server.php';
	public $port=80;

	private $client;

	public function __construct($host,$path,$port,$appName,$secKey){
		$this->host=$host;
		$this->path=$path;
		$this->port=$port;
		$this->appName=$appName;
		$this->secretKey=$secKey;

		$this->client=new xmlrpc_client($this->path,$this->host,$this->port);
		$this->client->return_type="phpvals";
		$this->client->setDebug(0);
	}


	public function createUser($username,$email,$password){

		return $this->callMethod("jc.host.createUser",array($username,$email,$password));
	}

	public function updateUser($username,$email,$password){

		return $this->callMethod("jc.host.updateUser",array($username,$email,$password));
	}

	public function deleteUser($username){

		return $this->callMethod("jc.host.deleteUser",array($username));
	}


	public function login($username,$password){
		return $this->callMethod("jc.host.login",array($username,$password));
	}

	public function logout($username){
		return $this->callMethod("jc.host.logout",array($username));
	}

	private function callMethod($methodName,$paramArray){
		$msg=new xmlrpcmsg($methodName);
		$msg->addParam(php_xmlrpc_encode($this->appName));
		$msg->addParam(php_xmlrpc_encode($this->secretKey));
		for($lc=0;$lc<sizeof($paramArray);$lc++){
			$msg->addParam(php_xmlrpc_encode($paramArray[$lc]));
		}

		$res =& $this->client->send($msg, 0, '');

		if($res->faultCode){
			throw new Exception("xmlrpc Error: ". $res->faultCode." :: ".$res->faultString);
		}
		else if($res->errno){
			throw new Exception("user Error: ". $res->errno." :: ".$res->errstr);
		}

		$varU=$res->value();
		if($varU['code']){
			throw new Exception("Joomla Error: ". $varU['code']." :: ".$varU['message']);
		}

		$cookies=$res->_cookies;
		foreach ($cookies as $i => $value) {
			$time=strtotime($cookies[$i]['expires']);
			setcookie($i,$cookies[$i]['value'],$time,$cookies[$i]['path']);
		}

		return $varU;
	}

}